/**
 * tabBar页面路径列表 (用于链接跳转时判断)
 * tabBarLinks为常量, 无需修改
 */
import Toast from './weapp/toast/toast'
const tabBarLinks = [
  'pages/index/index',
  'pages/social/pair',
  'pages/coupon/index',
  'pages/user/index'
];

// 工具类
const util = require('./utils/util.js');
// import '././utils/login'
App({

  /**
   * 全局变量
   */
  globalData: {
    user_id: null,
    referee_id: '',
    //room_id:''
  },
  toast(type,message,url){
    Toast({
      type,
      message,
      onClose: () => {
        wx.redirectTo({
          url
        })
      },
    });
  },
  // api地址
  api_root: '',
  root:'',
  siteInfo: require('siteinfo.js'),

  /**
   * 生命周期函数--监听小程序初始化
   */
  onLaunch: function(e) {
    // 设置api地址
    this.setApiRoot();
    this.setRoot();

    // 小程序主动更新
    this.updateManager();
    
    // 小程序启动场景
    this.onStartupScene(e.query);
  },

  /**
   * 小程序启动场景
   */
  onStartupScene: function(query) {
    // 获取场景值
    let scene = this.getSceneData(query);
    // 记录推荐人id
    let refereeId = query.referee_id ? query.referee_id : scene.uid;
    refereeId > 0 && (this.saveRefereeId(refereeId));

  },

  /**
   * 房间id
   */
  // saveRoomId: function (roomId) {
  //   if (!wx.getStorageSync('room_id'))
  //     wx.setStorageSync('room_id', roomId);
  // },


  /**
   * 记录推荐人id
   */
  saveRefereeId: function(refereeId) {
    if (!wx.getStorageSync('referee_id'))
      wx.setStorageSync('referee_id', refereeId);
  },

  /**
   * 获取场景值(scene)
   */
  getSceneData: function(query) {
    return query.scene ? util.scene_decode(query.scene) : {};
  },

  /**
   * 当小程序启动，或从后台进入前台显示，会触发 onShow
   */
  onShow: function(options) {
    // 获取小程序基础信息
    // this.getWxappBase();
    let token = wx.getStorageSync('token');
  },

  /**
   * 设置api地址
   */
  setApiRoot: function() {
    this.api_root = this.siteInfo.siteroot;
  },

  /**
   * 设置api地址
   */
  setRoot: function () {
    this.root = this.siteInfo.siteroot;
  },

  /**
   * 获取小程序基础信息
   */
  // getWxappBase: function(callback) {
  //   let App = this;
  //   App._get('wxapp/base', {}, function(result) {
  //     // 记录小程序基础信息
  //     wx.setStorageSync('wxapp', result.data.wxapp);
  //     callback && callback(result.data.wxapp);
  //   });
  // },

  /**
   * 执行用户登录
   */
  doLogin: function() {
    // 保存当前页面
    let pages = getCurrentPages();
    if (pages.length) {
      let currentPage = pages[pages.length - 1];
      "pages/login/login" != currentPage.route &&
        wx.setStorageSync("currentPage", currentPage);
    }
    // 跳转授权页面
    // wx.navigateTo({
    //   url: "/pages/login/login"
    // });
  },

  goDoLogin:function(){
    wx.redirectTo({
      url: '/pages/login/login'
    })
  },

  /**
   * 当前用户id
   */
  getUserId: function () {
    return wx.getStorageSync('user_id');
  },
  
  getRefereeId: function () {
    return wx.getStorageSync('referee_id');
  },
  /**
   * 显示成功提示框
   */
  showSuccess: function(msg, callback) {
    wx.showToast({
      title: msg,
      icon: 'success',
      mask: true,
      duration: 1500,
      success: function() {
        callback && (setTimeout(function() {
          callback();
        }, 1500));
      }
    });
  },

  /**
   * 显示失败提示框
   */
  showError: function(msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function(res) {
        // callback && (setTimeout(function() {
        //   callback();
        // }, 1500));
        callback && callback();
      }
    });
  },

  /**
   * 显示失败提示框
   */
  showIsLogin: function (msg, callback) {
    wx.showModal({
      title: '友情提示',
      content: msg,
      showCancel: false,
      success: function (res) {
        //wx.navigateBack();
        callback && callback();
      }
    });
  },


  /**
   * post提交
   */
  _post_fangx: function(url, data, success, fail, complete) {
    let App = this;
    // data.token = wx.getStorageSync('token');
    wx.request({
      url: 'https://p.t.fangx999.com/' + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: data,
      success: function(res) {
        wx.stopPullDownRefresh() //刷新完成后停止下拉刷新动效
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          // App.showError('网络请求出错');
          return false;
        }

        if(res.data.code == -1){
          wx.showModal({
            title: '友情提示',
            content: res.data.msg,
            showCancel: false,
            success: function(res2) {
              wx.redirectTo({
                url: '/pages/login/login'
              })
            }
          });
          wx.hideNavigationBarLoading();
        }
        success && success(res.data);
      },
      fail: function(res) {
        console.log(res);
        App.showError(res.errMsg, function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideNavigationBarLoading();
        // wx.hideLoading();
        complete && complete(res);
      }
    });
  },

  _post_form: function(url, data, success, fail, complete) {
    let App = this;
    data.token = wx.getStorageSync('token');
    let api_root = wx.getStorageSync('api_root')
    if(api_root){
      App.api_root = api_root;
    }
    var pages = getCurrentPages()    //获取加载的页面
    var currentPage = pages[pages.length-1]    //获取当前页面的对象
    // var url = currentPage    //当前页面url
    wx.setStorageSync('urlR', currentPage.route)
    // console.log(currentPage.route)
    console.log(App.api_root);
    console.log(data.token);
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: data,
      success: function(res) {
        wx.stopPullDownRefresh() //刷新完成后停止下拉刷新动效
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          App.showError('网络请求出错');
          return false;
        }

        if(res.data.code == -1){
          wx.showModal({
            title: '友情提示',
            content: res.data.msg,
            showCancel: false,
            success: function(res2) {
              wx.redirectTo({
                url: '/pages/login/login'
              })
            }
          });
          wx.hideNavigationBarLoading();
        }
        success && success(res.data);
      },
      fail: function(res) {
        console.log(res);
        App.showError(res.errMsg, function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideNavigationBarLoading();
        // wx.hideLoading();
        complete && complete(res);
      }
    });
  },

  /**
   * 图片post提交
   */
  _post_file: function(url, data, success, fail, complete) {
    let App = this;
    // data.wxapp_id = App.siteInfo.uniacid;
    // data.user_id = '5B83743F-D7C1-91F4-661E-FE010F7F059D'
    //console.log(1111);
    // data.token = wx.getStorageSync('token');
    wx.showNavigationBarLoading();
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: data,
      success: function(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          // App.showError('网络请求出错');
          return false;
        }
        if (res.data.code === -1) {
          // 登录态失效, 重新登录
          wx.hideNavigationBarLoading();
          //App.doLogin();
          return false;
        } 
        // else if (res.data.code === 0) {
        //   App.showError(res.data.msg, function() {
        //     // fail && fail(res);
        //     success && success(res.data);
        //   });
        //   return false;
        // }
        success && success(res.data);
      },
      fail: function(res) {
        console.log(res);
        App.showError(res.errMsg, function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideNavigationBarLoading();
        // wx.hideLoading();
        complete && complete(res);
      }
    });
  },
//带有提交loading请求
  _post: function(url, data, success, fail, complete) {
    let App = this;
    data.token = wx.getStorageSync('token');
    wx.showLoading({
      title: '提交中...',
    })
    wx.request({
      url: App.api_root + url,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      method: 'POST',
      data: data,
      success: function(res) {
        if (res.statusCode !== 200 || typeof res.data !== 'object') {
          // App.showError('网络请求出错');
          return false;
        }

        // if(res.data.code == -1){
        //   wx.showModal({
        //     title: '友情提示',
        //     content: res.data.msg,
        //     showCancel: false,
        //     success: function(res2) {
        //       wx.redirectTo({
        //         url: '/pages/login/login'
        //       })
        //     }
        //   });
        //   wx.hideNavigationBarLoading();
        //   // App.goDoLogin();
        // }
        success && success(res.data);
      },
      fail: function(res) {
        console.log(res);
        App.showError(res.errMsg, function() {
          fail && fail(res);
        });
      },
      complete: function(res) {
        wx.hideNavigationBarLoading();
        wx.hideLoading();
        complete && complete(res);
      }
    });
  },

  /**
   * 验证是否存在user_info
   */
  validateUserInfo: function() {
    let user_info = wx.getStorageSync('user_info');
    return !!wx.getStorageSync('user_info');
  },

  /**
   * 对象转URL
   */
  urlEncode: function(data) {
    var _result = [];
    for (var key in data) {
      var value = data[key];
      if (value.constructor == Array) {
        value.forEach(function(_value) {
          _result.push(key + "=" + _value);
        });
      } else {
        _result.push(key + '=' + value);
      }
    }
    return _result.join('&');
  },

  /**
   * 小程序主动更新
   */
  updateManager: function() {
    if (!wx.canIUse('getUpdateManager')) {
      return false;
    }
    const updateManager = wx.getUpdateManager();
    updateManager.onCheckForUpdate(function(res) {
      // 请求完新版本信息的回调
      // console.log(res.hasUpdate)
    });
    updateManager.onUpdateReady(function() {
      wx.showModal({
        title: '更新提示',
        content: '新版本已经准备好，即将重启应用',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
            updateManager.applyUpdate()
          }
        }
      });
    });
    updateManager.onUpdateFailed(function() {
      // 新的版本下载失败
      wx.showModal({
        title: '更新提示',
        content: '新版本下载失败',
        showCancel: false
      })
    });
  },

  /**
   * 获取tabBar页面路径列表
   */
  getTabBarLinks: function() {
    return tabBarLinks;
  },

  /**
   * 跳转到指定页面
   * 支持tabBar页面
   */
  navigationTo: function(url) {
    if (!url || url.length == 0) {
      return false;
    }
    let tabBarLinks = this.getTabBarLinks();
    // tabBar页面
    if (tabBarLinks.indexOf(url) > -1) {
      wx.switchTab({
        url: '/' + url
      });
    } else {
      // 普通页面
      wx.navigateTo({
        url: '/' + url
      });
    }
  },

  /**
   * 记录formId
   */
  saveFormId: function(formId) {
    let App = this;
    //console.log('saveFormId');
    if (formId === 'the formId is a mock one') {
      return false;
    }
    App._post_form('wxapp.formId/save', {
      formId: formId
    });
  },

  /**
   * 获取当前用户信息
   */
  getUserDetail: function () {
    let _this = this;
    _this._get('user.index/detail', {}, function (result) {
      //_this.setData(result.data);
      let user_address_id = wx.getStorageSync('user_address_id');
      //console.log(user_address_id);
      //如果用户表地址id  和 缓存id 不一致就重新定位  
      // if (result.data.userInfo.user_address_id != user_address_id ){
      //   _this.getLocation();
      // }
      _this.getLocation();
    });
  },

  //定位到当前位置，并存入缓存
  getLocation: function () {
    let _this = this;
    wx.getLocation({ //没有特别说明的都是固定写法
      type: 'gcj02',
      success: function (res) {
        //console.log('location', res);
        let locationString = res.latitude + "," + res.longitude;
        _this.form_localhost(locationString);
      }
    });
  },


  form_localhost: function (locationString){
    let _this = this;
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/',
      data: {
        "key": "AW5BZ-G5T3U-LWBV6-4JUDZ-7CU7V-ANFVB",
        "location": locationString
      },
      method: 'GET',
      success: function (r) {
        //console.log(r);
        //console.log(r.data.result.address_reference.landmark_l2.id);
        let user_address_id = r.data.result.address_reference.landmark_l2.id;
        let user_address_cont = r.data.result.address_reference.landmark_l2.title;
        //城市
        let shoppingMallCity = r.data.result.address_component.city;
        //区
        let shoppingMallDistrict = r.data.result.address_component.district;
        //输出一下位置信息
        //console.log('用户位置信息', r.data.result.address);
        try {
          wx.setStorageSync('shopping_mall_city', shoppingMallCity);
          wx.setStorageSync('shopping_mall_district', shoppingMallDistrict);
          wx.setStorageSync('user_address_id', user_address_id);
          wx.setStorageSync('user_address_cont', user_address_cont);
        } catch (e) {
          console.log(e)
        }

        _this._post_form('user.index/set_user_address_id', { 
          user_address_id: user_address_id, 
          user_address_cont: user_address_cont, 
          shopping_mall_city: shoppingMallCity, 
          shopping_mall_district: shoppingMallDistrict
          }, 
          function (result) {
          //console.log(result);
        }, false, function () {
          // 解除禁用

        });
      }
    });
  }


});